<template>
  <div id="userProfileView">
    <!-- 顶部卡片展示个人信息 -->
    <a-card style="margin-bottom: 20px;">
      <template #extra>
        <h3 @click="editUserInfo">编辑 ></h3>
      </template>
      <UserAvatar
          :user-id="loginUserStore.loginUser.id"
          :avatar-size="64"
          :font-size="18"
      />
      <p style="margin-top: 16px;">{{loginUserStore.loginUser.userProfile}}</p>
    </a-card>
    <!-- 顶部菜单栏 -->
    <a-menu mode="horizontal" :selectedKeys="selectedKeys" @menu-item-click="doMenuClick">
      <a-menu-item key="/userProfile/myPost">
        我的发布
      </a-menu-item>
      <a-menu-item key="/userProfile/myFavour">
        我的收藏
      </a-menu-item>
      <a-menu-item key="/userProfile/myFinish">
        已完成
      </a-menu-item>
    </a-menu>
    <!-- 底部详细信息 -->
    <div style="padding: 20px;">
      <!-- 动态渲染子路由 -->
      <RouterView></RouterView>
    </div>
    <!-- 侧边栏显示修改的用户信息-->
    <a-drawer :width="450" :visible="editVisible" @ok="doEditUser" @cancel="editVisible=false" unmountOnClose>
      用户名：<a-input v-model="userInfo.userName"/>
      密码：<a-input v-model="userInfo.userPassword"/>
      简介：<a-input v-model="userInfo.userProfile"/>
      <file-upload @onProgress="onProgress"></file-upload>
    </a-drawer>
  </div>
</template>

<script setup>
import { useLoginUserStore } from "@/store/userStore";
import {  ref } from "vue";
import { useRouter } from "vue-router";
import {updateMyUserUsingPost} from "@/api/UserRequest";
import FileUpload from "@/components/FileUpload.vue";
import {uploadFileUsingPost} from "@/api/FileRequest";
import message from "@arco-design/web-vue/es/message";
import UserAvatar from "@/components/UserAvatar.vue";

// 定义抽屉是否显示
const editVisible = ref(false);

const userInfo = ref({
  userName: '',
  userPassword: '',
  userProfile: '',
  userAvatar: '',
})

const loginUserStore = useLoginUserStore();
const router = useRouter();
const file = ref();

// 当前选中的菜单项
const selectedKeys = ref(["/"]);
// 路由跳转时，自动更新选中的菜单项
router.afterEach((to) => {
  selectedKeys.value = [to.path];
});

// 点击菜单后更改路由
const doMenuClick = (key) => {
  router.push({
    path: key,
  });
};

function editUserInfo(){
  Object.assign(userInfo.value, loginUserStore.loginUser);
  editVisible.value=true;
}

async function doEditUser(){
  try {
    if(file.value){
      const result = await uploadFileUsingPost(file.value , "user_avatar");
      userInfo.value.userAvatar = result.data.data;
    }
    await updateMyUserUsingPost(userInfo.value);
    editVisible.value=false;
    await loginUserStore.fetchLoginUser();
    userInfo.value = {};
    message.success('用户信息更新成功');
  } catch (error) {
    message.error('用户信息更新失败，请重试');
    console.error('用户信息更新失败:', error);
  }
}

function onProgress(currentFile){
  file.value = currentFile.file;
  console.log(currentFile.file);
}
</script>

<style scoped>
#userProfileView {
  padding: 20px;
}
</style>